package com.shanghaionstar.report.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by 6335yz on 2016/11/9.
 * 线程池，提供一个单列线程池供report 功能等调用
 */
public class PoolThread {

    private int maxThread = 5;

    private Queue<Runnable> tasks =  new LinkedBlockingQueue<Runnable>();

    private List<Thread> pollThreads;

    private boolean isOn = false;

    public PoolThread(int maxThread) {
        this.maxThread = maxThread;
        isOn = false;
        pollThreads = new ArrayList<>();
        for (int i = 0; i < maxThread; i++) {
            pollThreads.add(new Thread(new SingleThread()));
        }
    }

    public void start() {
        this.isOn = true;
        for (int i = 0; i < maxThread; i++) {
            pollThreads.get(i).start();
        }
    }

    public boolean isOn() {
        return isOn;
    }

    public void execute(Runnable task) {
        synchronized (tasks) {
            tasks.add(task);
            tasks.notifyAll();
        }
    }

    public void shutDown() {
        this.isOn = false;
    }

    class SingleThread implements Runnable {
        @Override
        public void run() {
            while (isOn) {
                synchronized (tasks) {
                    Runnable task = tasks.poll();   //取出任务队列中的任务执行
                    if (task != null)
                        task.run();
                    if (tasks.size() == 0) {    //如果队列中没有等待的任务，则停止线程，直到有任务加进队列时唤醒该线程
                        try {
                            tasks.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
